<template>
	<view>
		<create-form-container ref="form" :form-disable="formDisable" :flow="flow" :datasource="dataSource"></create-form-container>
		<create-btn-bar :dataSource="toolBarData" :hideSend="hideSend" @btnClick="btnClick"></create-btn-bar>
		<result-modal :visible="resultVisible" :msg="resultMsg" @ok-click="resultOkClick" @cancel-click="resultCancelClick"></result-modal>
		<return-modal :visible="returnVisible" :flow="flow" @close-modal="closeReturnModal" @ok-click="returnOkClick"></return-modal>
		<select-accepter-modal :visible="selectAccepterVisible" :flow="flow" :accepter-type="1" :to-node="toNode" @send-click="selectOkClick" @close-modal="closeAccepterModal"></select-accepter-modal>
	</view>
</template>

<script>
import { mapActions, mapMutations } from 'vuex';
import loginMixin from '../../mixins/loginMixin.js';
import qs from 'qs';
import CreateFormContainer from './components/create-form-container/create-form-container.vue'
import CreateBtnBar from './components/create-btn-bar/create-btn-bar.vue'
export default {
	components:{
		CreateFormContainer,
		CreateBtnBar
	},
	mixins: [loginMixin],
	onLoad(obj) {
		console.log('onload',obj)
		this.flow.WorkID = obj.WorkID;
		this.flow.FK_Node = obj.FK_Node;
		this.flow.FK_Flow = obj.FK_Flow;
		this.flow.FID = obj.FID;
		if (obj.formDisable === true || obj.formDisable === 'true') {
			this.formDisable = true;
		}
		if (obj.forceSend === true || obj.forceSend === 'true') {
			this.forceSend = true;
		}
		this.hideSend = obj.hideSend;
		this.pageType = obj.type;
	},
	data() {
		return {
			loading: false,
			formDisable: false,
			flow: {},
			dataSource: {},
			pageReady: false,
			hideSend: 'false',
			pageType: 'view',
			toolBarData: {},
			resultVisible: false,
			resultMsg: '',
			returnVisible: false,
			forceSend: false,
			selectAccepterVisible: false,
			toNode: '',
			accepterType: 1
		};
	},
	computed: {
		allReady() {
			return this.$store.state.appReady && this.pageReady;
		}
	},
	watch: {
		allReady: {
			deep: true,
			immediate: true,
			handler(val) {
				if (val) {
					this.initData();
				}
			}
		},
		appReady: {
			deep: true,
			immediate: true,
			handler(val) {
				if (val) {
					this.handleLogin()
						.then(() => {
							this.pageReady = true;
						})
						.catch(() => {
							uni.showModal({
								title: '提示',
								content: '登录信息丢失，请重新登录',
								success(res) {
									if (res.confirm) {
										uni.redirectTo({
											url: 'pages/index/index'
										});
									}
								}
							});
						});
				}
			}
		}
	},
	beforeDestroy() {
		this.dataSource = {}
	},
	methods: {
		...mapActions({
			generWorkFlow: 'flow/generWorkFlow',
			getNodeMsg: 'flow/getNodeMsg',
			frmGenerInit: 'flow/frmGenerInit',
			sendFlow: 'flow/sendFlow',
			entityInit: 'flow/entityInit',
			unSendFlow: 'flow/unSendFlow',
			returnFlow: 'flow/returnFlow',
			forceAccepter: 'flow/forceAccepter',
			accepterSend: 'flow/accepterSend'
		}),
		initData() {
			uni.showLoading({
				mask: true
			});
			this.getNodeMsg({
				PKVal: this.flow.FK_Node
			})
				.then(res => {
					return this.frmGenerInit({
						...this.flow,
						UserNo: this.$store.state.user.userInfo.No,
						SID: this.$store.state.user.userInfo.SID,
						IsReadonly: 1,
						DoTypeDel: 'xxHttpHandler',
						PKVal: this.flow.WorkID,
						OID: this.flow.WorkID,
						FK_MapData: res.NodeFrmID || `ND${this.flow.FK_Node}`
					});
				})
				.then(res => {
					console.log(res);
					this.dataSource = { ...res };
					this.$forceUpdate();
					uni.hideLoading();
					uni.setNavigationBarTitle({
						title: `${res.WF_Node[0].FlowName}-${res.WF_Node[0].Name}`
					});
					return this.getOpeNode(this.flow.FK_Node);
				})
				.then(res => {
					console.log(res);
				})
				.catch(err => {
					console.log(err);
				});
		},
		getOpeNode(PKVal) {
			return new Promise((resolve, reject) => {
				this.entityInit({ PKVal })
					.then(res => {
						if (this.pageType == 'add' || this.pageType == 'detail') res.SendEnable = 1;
						if (this.hideSend != 'false') {
							console.log('hideSend', this.hideSend);
							res.SendEnable = 0;
						}
						this.toolBarData = res;
						resolve(res);
					})
					.catch(err => {
						reject(err);
					});
			});
		},
		selectOkClick(obj) {
			uni.showLoading({
				title: '请求中'
			});
			if (obj && obj.selectEmps) {
				this.accepterSend({
					...this.flow,
					ToNode: this.toNode,
					SelectEmps: obj.selectEmps.join(';')
				})
					.then(res => {
						console.log(res);
						uni.hideLoading();
						this.selectAccepterVisible = false
						this.resultMsg = res;
						this.resultVisible = true;
					})
					.catch(err => {
						console.log(err);
						uni.hideLoading();
					});
			} else {
				this.sendFlow({
					...this.flow,
					ToNode: this.toNode
				})
					.then(res => {
						uni.hideLoading();
						this.selectAccepterVisible = false
						this.resultMsg = res;
						this.resultVisible = true;
					})
					.catch(err => {
						console.log(err);
						uni.hideLoading();
					});
			}
		},
		sendClick() {
			let self = this;
			this.$refs.form
				.validateAndSend()
				.then(res => {
					console.log('validateSuc', res);
					uni.showLoading({
						title: '请求中'
					});
					return self.sendFlow({ ...res, ...self.flow });
				})
				.then(res => {
					uni.hideLoading();
					let params = {};
					if (res.includes('Accepter.htm')) {
						try {
							params = qs.parse(res.split('?')[1]);
							this.toNode = params.ToNode;
						} catch (error) {
							console.log(error);
						}
						this.accepterType = 2;
						this.selectAccepterVisible = true;
					} else if (res.includes('AccepterOfGener.htm')) {
						try {
							params = qs.parse(res.split('?')[1]);
							this.toNode = params.ToNode;
						} catch (error) {
							console.log(error);
						}
						this.accepterType = 1;
						this.selectAccepterVisible = true;
					} else {
						this.resultMsg = res;
						this.resultVisible = true;
					}
				})
				.catch(err => {
					console.log('validateFail', err);
				});
		},
		forceChangeAccepter() {
			return new Promise((resolve, reject) => {
				this.forceAccepter({
					TB_NodeID: this.flow.FK_Node,
					TB_Worker: this.$store.state.user.userInfo.No,
					PKVal: this.flow.FK_Flow,
					TB_WorkID: this.flow.WorkID
				}).then(res => {
					console.log(res);
					if (res && res.includes('执行成功')) {
						resolve();
					} else {
						reject(res);
					}
				});
			});
		},
		btnClick(obj) {
			let self = this;
			switch (obj.type) {
				case 'SendEnable': {
					uni.showModal({
						title: '提示',
						content: '确定发送？',
						success(res) {
							if (res.confirm) {
								if (self.forceSend) {
									self.forceChangeAccepter()
										.then(() => {
											return self.sendClick();
										})
										.catch(err => {
											console.log(err);
											uni.showModal({
												title: '提示',
												content: err,
												showCancel: false,
												success: function(res) {
													if (res.confirm) {
														console.log('用户点击确定');
													}
												}
											});
										});
								} else {
									self.sendClick();
								}
							}
						}
					});

					break;
				}
				case 'ReturnRole': {
					this.returnVisible = true;
					break;
				}
			}
		},
		resultOkClick() {
			this.resultVisible = false;
			uni.navigateBack({});
		},
		resultCancelClick() {
			let self = this;
			uni.showModal({
				title: '撤销发送',
				content: '确定撤销发送？',
				success(res) {
					if (res.confirm) {
						self.unSendFlow({ ...self.flow }).then(res => {
							console.log(res);
							res = res.replace('@', '');
							res = res.replace(/null+/g, '');
							uni.showModal({
								title: '撤销发送',
								content: res,
								showCancel: false,
								success() {
									self.resultVisible = false;
									uni.navigateBack({});
								}
							});
						});
					} else {
					}
				}
			});
		},
		closeReturnModal() {
			this.returnVisible = false;
		},
		closeAccepterModal(){
			this.selectAccepterVisible = false;
		},
		returnOkClick(obj) {
			let self = this;
			this.returnFlow({
				...obj,
				...this.flow
			})
				.then(res => {
					console.log(res.split(/\n/));
					uni.showModal({
						title: '结果',
						content: res.split(/\n/)[0],
						showCancel: false,
						success() {
							self.returnVisible = false;
							uni.navigateBack({});
						}
					});
				})
				.catch(err => {
					console.log(err);
				});
		}
	}
};
</script>

<style lang="less">
.opeCon {
	padding: 24rpx 12rpx;
	display: flex;
	flex-wrap: wrap;
	justify-content: space-around;
	.opeItem {
		flex: 1;
		max-width: 50%;
		padding: 12rpx;
		button {
			width: 100%;
		}
	}
}
</style>
